package test.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public final class SocketClient{

	private final String responseTailSignal = "Enter command:";
	private final int responseTailSignalLength = responseTailSignal.length();

	private char[] buffer = new char[512];

	private Socket socketClient;

	private BufferedReader socketIn;
	private PrintWriter socketOut;

	public SocketClient(){
		try {
			socketClient = new Socket("127.0.0.1", 3300);
			socketClient.setSoTimeout(6000);
			socketIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
			socketOut = new PrintWriter(socketClient.getOutputStream(),true /* autoFlush */);

			getResponse();	//CONNECT
		} catch (IOException e) {
			throw new RuntimeException("Can not connect to the server!");
		}
	}

	public String getResponse() throws IOException {
		StringBuffer stringBuffer = new StringBuffer();

		int num;
		int count = 0;
		boolean isTheEnd = false;
		while (!isTheEnd && (num = socketIn.read(buffer)) > 0) {
			//some tricky error, such as disconnect and no response from the server
			if(count==0 && !(buffer.toString().startsWith("RESP") || buffer.toString().startsWith("CONNECT"))){
				throw new RuntimeException("Can not connect to the server!");
			}
			
			stringBuffer.append(buffer, 0, num);
			//when meet "Enter Command:", it means the end of the response and we should remove the data after "Enter Command:" in buffer 
			int index = stringBuffer.indexOf(responseTailSignal);
			if (index > -1) {
				stringBuffer.delete(index, index + responseTailSignalLength);
				isTheEnd = true;
			}
			count++;
		}

		return new String(stringBuffer.toString().trim().getBytes(), "UTF8");
	}

	public void sendRequest(String output) throws IOException {
		socketOut.println(output);
	}
	
	public void disconnect(){
		try {
			if(socketIn!=null){
				socketIn.close();
				socketIn = null;
			}
			if(socketOut!=null){
				socketOut.close();
				socketOut = null;
			}
			if(socketClient!=null){
				socketClient = null;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
